<template>
  <div class="ibk">
    <template v-for="tag in tags">
      <a-tooltip v-if="tag.length > 8" :key="`tip${tag}`" :title="tag">
        <a-tag
          style="cursor:pointer"
          :key="tag"
          @click="() => handleClick(tag)">
          {{ `${tag.slice(0, 8)}...` }}<i class="ml10 fa fa-remove" @click.stop="handleDel(tag)"></i>
        </a-tag>
      </a-tooltip>
      <a-tag
        style="cursor:pointer"
        v-else
        :key="tag"
        @click="() => handleClick(tag)">
        {{ tag }}<i class="ml10 fa fa-remove" @click.stop="handleDel(tag)"></i>
      </a-tag>
    </template>
    <a-input
      v-if="inputVisible"
      ref="input"
      type="text"
      size="small"
      :style="{ width: '78px' }"
      :value="inputValue"
      @change="handleInputChange"
      @blur="handleInputConfirm"
      @keyup.enter="handleInputConfirm"
    />
    <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
      <a-icon type="plus" /> 添加
    </a-tag>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'modelVal', // 指向props的参数名
    event: 'change'// 事件名称
  },
  props: {
    modelVal: {
      type: Array,
      default: () => { return [] }
    }
  },
  data () {
    return {
      tags: this.modelVal,
      inputVisible: false,
      inputValue: ''
    }
  },
  watch: {
    modelVal (newVal) {
      this.tags = newVal
    },
    tags (newVal) {
      this.$emit('change', newVal)
    }
  },
  methods: {
    handleDel (delTag) {
      const that = this
      that.$confirm({ title: '确定删除这条记录么',
        onOk () {
          const tags = that.tags.filter(tag => tag !== delTag)
          that.tags = tags
          that.$emit('del', delTag)
        }
      })
    },

    handleClick (tag) {
      this.$emit('click', tag)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(function () {
        this.$refs.input.focus()
      })
    },

    handleInputChange (e) {
      this.inputValue = e.target.value
    },

    handleInputConfirm () {
      const inputValue = this.inputValue
      let tags = this.tags
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue]
        this.$emit('add', inputValue)
      }
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: ''
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
